package com.treeroot.treenet.strategy;

import com.treeroot.treenet.enums.ProtocolTypeMenu;
import com.treeroot.treenet.strategy.init.InitStrategyImpl;
import com.treeroot.treenet.strategy.init.InitStrategyService;

import java.util.HashMap;
import java.util.Map;

/**
 * Create By TreeRoot
 * Create Time: 2023/12/11 09:35
 * Class Name: ProtocolStrategyHandlerContext
 * Description:
 * 协议策略上下文
 * @author TreeRoot
 */
public class ProtocolStrategyContext {
    private static final InitStrategyService initStrategyService = new InitStrategyImpl();
    private static final Map<ProtocolTypeMenu, ProtocolStrategyHandle> BIZ_HANDLER_MAP = new HashMap<>();
    private static volatile ProtocolStrategyContext instance;

    public static ProtocolStrategyContext getInstance() {
        if (instance == null) {
            synchronized (ProtocolStrategyContext.class) {
                if (instance == null) {
                    instance = new ProtocolStrategyContext();
                    BIZ_HANDLER_MAP.putAll(initStrategyService.getProtocolStrategyHandleMap());
                }
            }
        }
        BIZ_HANDLER_MAP.putAll(initStrategyService.getProtocolStrategyHandleMap());
        return instance;
    }

    /**
     * 执行请求
     *
     * @param requestType 请求类型
     *                    2023/11/06
     */
    public void execute(ProtocolTypeMenu requestType) {
        ProtocolStrategyHandle protocolStrategyHandle = BIZ_HANDLER_MAP.get(requestType);
        if (protocolStrategyHandle == null) {
            throw new IllegalArgumentException("not found handler for requestType: " + requestType);
        }
        protocolStrategyHandle.handleRequest(requestType);
    }
}
